#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time    : 2019-10-29 16:24
@Author  : wangb
@Email   : joker_wb@163.com
@File    : main.py
@Software: PyCharm
"""
import multiprocessing as mp
import json
import os
import sys
from multiprocessing import Queue
from utils import configloader as cfg
import requests
from logger import LOG
from redisutils import RedisUtils
from utils import configloader
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime

from utils.date_utils import DateUtils, DataStatus
from utils.image_utils import image_put, get_init_image, process_imgs

du = DateUtils()
redis_utils = RedisUtils(host=configloader.redis_host(), port=configloader.redis_port())
scheduler = BackgroundScheduler()


@scheduler.scheduled_job('interval', seconds=10)
def get_time():
    time_results = du.checkssss(datetime.now(), redis_client)
    if isinstance(time_results.get('code'), DataStatus):
        time_results['code'] = time_results.get('code').value
    redis_client.set(configloader.time_results(), json.dumps(time_results, ensure_ascii=False))
    LOG.info("scheduler task get time executed!,now time_results is {0}", time_results)


def method_init():
    """
    初始化方法
    :return:
    """
    try:
        headers = {
            "license": "e10adc3949ba59abbe56e057f20f883e"
        }

        response = requests.post(cfg.get_rtsp_api_url(), headers=headers)
        # response = requests.post('http://127.0.0.1:8080/smart/duty/getRtsp?type=1', headers=headers)
        LOG.info("response content is {0}".format(response.content))
        request_result = json.loads(response.content)
        if request_result.get('success'):
            web_camera_data = request_result.get('dataInfo')

            camera_config = {}
            prefix = "camera:"
            for index, camera in enumerate(web_camera_data):
                camera_config[prefix + str(index)] = camera

            with open('config/camera_config.json', 'w') as f:
                json.dump(camera_config, f, ensure_ascii=False)

            return web_camera_data
        else:
            LOG.error("init method error，exit!")
            sys.exit(0)
    except Exception as e:
        LOG.error("method init error ,the error is {0}".format(e.args[0]))
        sys.exit(0)


"""
第一步，先初始化。发送消息，获得到camera的信息
1. 调用外部的的视频流获取接口，返回所有视频流数据数组！
2. 然后外部调用我的图片描述接口。
3. 然后我描好点把工位对象调你接口传给你！最后再调用配置接口把监控时间等参数给你！
4. 如果有警情你调用我的接口把警情发给我就OK！
5. 你那边可能需要再写一个工位监控人员更新接口，方便人员更新和报警接口调用传给我参数
"""

if __name__ == '__main__':
    LOG.info("main function start!")
    scheduler.start()
    staff_status = mp.Manager().dict()

    redis_client = redis_utils.get_redis()
    # clear redis
    redis_client.delete(cfg.time_results())
    q_out = Queue(10)
    """1.第一步，先初始化。发送消息，获得到camera的信息"""
    web_camera_data = method_init()

    """获取初始化图片"""
    for camera in web_camera_data:
        rtsp = camera.get('rtsp')
        camera_num = camera.get('cameraNum')
        result = get_init_image(rtsp=rtsp, camera_num=camera_num)
        if not result.get("success"):
            os.remove('camera_images')
            LOG.info("rtsp error！")
            sys.exit(0)

    processes = []
    for i in range(len(web_camera_data)):
        processes.append(mp.Process(target=image_put, args=(q_out, web_camera_data[i], staff_status, redis_client,),name="camera {0}".format(i)))
    processes.append(mp.Process(target=process_imgs, args=(q_out, staff_status, redis_client)))

    for process in processes:
        process.start()

    [process.join() for process in processes]
